﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Lucas.Wendell.PI.Model;
using Lucas.Wendell.PI.Service;

namespace Lucas.Wendell.PI.WebSite.AuthorizationAccess
{
    public class AuthorizationAttribute : AuthorizeAttribute
    {
        private Usuario _usuario;

        public Usuario Usuario
        {
            get
            {
                HttpCookie cookie = null;

                if (HttpContext.Current != null)
                    cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
                if (cookie != null)
                {
                    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
                    if (ticket != null)
                        if (_usuario == null || !_usuario.Id.ToString(CultureInfo.InvariantCulture).Equals(ticket.UserData))
                            return _usuario = new UsuarioService().GetById(Convert.ToInt32(ticket.UserData));

                    return _usuario;
                }

                return _usuario = null;
            }
        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            //Renew browser cook for authentication
            if (this.Usuario != null && filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                double cookieTimeout;
                Double.TryParse(System.Configuration.ConfigurationManager.AppSettings["cookieTimeOut"], out cookieTimeout);

                var authTicket = new FormsAuthenticationTicket(
                    1,
                    this.Usuario.Login,
                    DateTime.Now,
                    DateTime.Now.AddHours(cookieTimeout),
                    true,
                    this.Usuario.Id.ToString(CultureInfo.InvariantCulture));

                var authCookie = FormsAuthentication.GetAuthCookie(this.Usuario.Login, true);
                authCookie.Expires = authTicket.Expiration;
                authCookie.Value = FormsAuthentication.Encrypt(authTicket);
                HttpContext.Current.Response.Cookies.Add(authCookie);
            }
            else
            {
                filterContext.Result = new RedirectResult("~/Account/Logon");
                return;
            }

            this.CheckPermission(filterContext, base.Roles.Split(','));

            if (filterContext.Result is HttpUnauthorizedResult)
            {
                filterContext.Result = new RedirectResult("~/Account/Denied");
                return;
            }
        }

        private void CheckPermission(AuthorizationContext filterContext, IEnumerable<string> roles)
        {
            //PermissaoService service = new PermissaoService();
            foreach (string role in roles)
            {
                if (role.Equals(""))
                    return;
                //if (service.CheckPermissionByUsuario(Convert.ToInt16(role), Usuario.Codigo) || Usuario.IsMaster)
                //    return;
            }

            filterContext.Result = new HttpUnauthorizedResult();
            return;
        }
    }
}